package com.example.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.constants.WemediaConstants;
import com.example.model.wemedia.dto.NewsDto;
import com.example.model.wemedia.pojo.Material;
import com.example.model.wemedia.pojo.News;
import com.example.model.wemedia.pojo.NewsMaterial;
import com.example.utils.thread.UserThreadLocal;
import com.example.wemedia.mapper.MaterialMapper;
import com.example.wemedia.mapper.NewsMapper;
import com.example.wemedia.mapper.NewsMaterialMapper;
import com.example.wemedia.service.NewsService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
    @Autowired
    private MaterialMapper materialMapper;
    @Autowired
    private NewsMaterialMapper newsMaterialMapper;

    @Override
    public News saveOrUpdate(NewsDto newsDto, List<String> contentImages) {
        News news = new News();
        BeanUtils.copyProperties(newsDto, news);
        // 补充参数
        news.setUserId(UserThreadLocal.getUser().getUserId());
        news.setCreatedTime(new Date());
        news.setSubmitedTime(new Date());
        if (newsDto.getId() == null) {
            save(news);
        } else {
            // 删除关联关系
            removeById(Wrappers.< NewsMaterial >lambdaQuery().eq(NewsMaterial::getNewsId, newsDto.getId()));
            updateById(news);
        }
        // 保存新闻内容关系
        saveRelations(contentImages, news.getNewsId(), WemediaConstants.REFERENCE_CONTENT);
        // 保存新闻封面图片关系
        String images = news.getNewsImages();
        if (!StringUtils.isEmpty(images)) {
            String[] imageArray = org.springframework.util.StringUtils.commaDelimitedListToStringArray(images);
            saveRelations(Arrays.asList(imageArray), news.getNewsId(), WemediaConstants.REFERENCE_COVER);
        }
        // 获取封面图片
        List<String> coverImages = getConverImages(newsDto, contentImages, news);
        String imageString = StringUtils.join(coverImages, ",");
        news.setNewsImages(imageString);
        return news;
    }

    @Override
    public List< String > getContentImages(NewsDto newsDto) {
        List<String> images = new ArrayList<>();
        String content = newsDto.getContent();
        List< Map > contentImgs = JSONArray.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(contentImgs)) {
            return images;
        }
        for (Map contentImg : contentImgs) {
            String type = contentImg.get("type") + "";
            if ("image".equals(type)) {
                String url = contentImg.get("value") + "";
                images.add(url);
            }
        }
        return images;
    }

    @Override
    public List< String > getConverImages(NewsDto newsDto, List< String > contentImages, News news) {
        // 默认获取到的封面图片就是前端传的
        List<String> images = newsDto.getImages();
        // 处理自动封面
        if (newsDto.getType() == WemediaConstants.COVER_TYPE_AUTO) {
            int size = contentImages.size();
            if (size >= 3) {
                news.setArticleType(WemediaConstants.COVER_TYPE_THREE);
                images = contentImages.stream().limit(3).collect(Collectors.toList());
            } else if (size >= 1) {
                images = contentImages.stream().limit(1).collect(Collectors.toList());
                news.setArticleType(WemediaConstants.COVER_TYPE_ONE);
            } else {
                news.setArticleType(WemediaConstants.COVER_TYPE_NO);
            }
        }
        return images;
    }

    @Override
    public void saveRelations(List< String > images, Integer newsId, Short type) {
        if (CollectionUtils.isEmpty(images)) {
            return;
        }
        LambdaQueryWrapper< Material > wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Material::getMaterialUrl, images);
        List< Material > materialList = materialMapper.selectList(wrapper);
        // 获得所有的id
        List< Integer > materialIds = materialList.stream().map(Material::getId).collect(Collectors.toList());
        newsMaterialMapper.insertBatch(materialIds, newsId, type);
    }
}

